package org.ceteca.explica.core.installer;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.ceteca.explica.client.gui.ExplicaGUIBuilder;
import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.util.InstanceLocator;
import org.ceteca.javaglade.toolkit.swt.SwtWidget;
import org.eclipse.swt.widgets.Composite;

public class EntityLauncherFactory {
	private HashMap<SwtWidget, EntityLauncher> lEntLaunchers;
	private EntityOT entData;
	private Logger logger;
	
	public EntityLauncherFactory(EntityOT entData, Logger logger) {
		this.entData = entData;
		this.logger = logger;
		this.lEntLaunchers = new HashMap<SwtWidget, EntityLauncher>();
	}
	
	private void buildEntityLauncher(SwtWidget parentWidget) {
		InstanceLocator loc = new InstanceLocator(this.logger);
		EntityLauncher entLauncher = (EntityLauncher)loc.getClassInstance(this.entData.getEntityHelperClass());

		if (entLauncher != null) {
			entLauncher.setEntity(this.entData);
			entLauncher.initEntityLauncher(this.logger, ExplicaGUIBuilder.getInstance().getGUI(InterfaceExplica.EXPLICA_CORE_GLADE_NAME), parentWidget);
			
			this.addEntityLauncher(entLauncher, parentWidget);
		}
	}
	
	public void addEntityLauncher(EntityLauncher entLauncher, SwtWidget parentWidget) {
		this.lEntLaunchers.put(parentWidget, entLauncher);
	}
	
	public EntityLauncher getEntityLauncher(SwtWidget parentWidget) {
		if (parentWidget != null) {
			if (!this.lEntLaunchers.containsKey(parentWidget))
				this.buildEntityLauncher(parentWidget);

			return this.lEntLaunchers.get(parentWidget);
		}
		else 
			return null;
	}
	
	public String toString() {
		StringBuffer buf = new StringBuffer();
		if (this.lEntLaunchers != null && this.lEntLaunchers.size() > 0) {
			Iterator it = this.lEntLaunchers.keySet().iterator();
			while (it != null && it.hasNext()) {
				Object parentKey = it.next();
				buf.append(String.format("\n\t%s = %s", parentKey, this.lEntLaunchers.get(parentKey)));
			}
		}
		
		return buf.toString();
	}
}
